#pragma once

#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include "log.hpp"

namespace Client
{
    class tcpClient
    {
    public:
        tcpClient(const string &ip, const uint16_t &port) : _sockfd(-1), _serverip(ip), _serverport(port)
        {
        }

        void initClient()
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                logMessage(4, "socket errno");
                exit(1);
            }

            logMessage(1, "socket success");
        }

        // tcp的客户端要connect
        void run()
        {
            // 封装好信息
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
           

            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            // 等于0表示connet成功
            if (connect(_sockfd, (sockaddr *)&server, sizeof(server)) != 0)
            {
                logMessage(2, "connect errno");
            }
            else
            {
                logMessage(1, "connect success");

                // 连接成功就可以开始写数据和读数据了

                string line;
                while (1)
                {
                    cout << "请输入# ";
                    getline(cin, line);

                    write(_sockfd, line.c_str(), line.size());

                    // 还要读取服务器发回来的信息
                    char buffer[1024];

                    ssize_t n = read(_sockfd, buffer, sizeof(buffer) - 1);
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        cout << "server say" << buffer << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        ~tcpClient()
        {
            if (_sockfd >= 0)
            {
                close(_sockfd);
            }
        }

    private:
        int _sockfd;
        string _serverip;
        uint16_t _serverport;
    };
}